<template>
  <div style="border: 1px solid #eee">
    <el-row style="padding:10px;margin-bottom: 10px">
      <el-col align="left" :span="6">
        <el-button
          v-if="openModel === 'new'"
          size="mini"
          @click="handleTypeSave()"
          class="el-button--primary"
          >保存</el-button
        >
        <el-button
          v-else
          size="mini"
          @click="handleTypeUpdate()"
          class="el-button--primary"
          >更新</el-button
        >
        <el-button
          size="mini"
          @click="handleTypeDelete()"
          class="el-button--primary"
          >删除</el-button
        >
        <el-button
          size="mini"
          @click="back()"
          class="el-button--primary"
          icon="el-icon-back"
          >返回</el-button
        >
      </el-col>
      <el-col :span="18">
        <el-alert
          v-if="dataChanged"
          title="您有尚未保存的数据，请及时保存"
          type="warning"
        >
        </el-alert>
      </el-col>
    </el-row>
    <el-form size="mini" :model="typeDef" align="left" ref="typeForm">
      <el-form-item
        label="模型命名"
        :label-width="fieldLabelWidth"
        style="margin-top:-10px"
        prop="name"
        :rules="{ required: true, message: '请输入模型名', trigger: 'blur' }"
      >
        <el-input
          v-model="typeDef.name"
          :readonly="openModel === 'update'"
        ></el-input>
      </el-form-item>
      <el-form-item
        size="mini"
        label="显示名称"
        :label-width="fieldLabelWidth"
        style="margin-top:-10px"
        prop="displayName"
        :rules="{
          required: true,
          message: '请输入模型显示名称',
          trigger: 'blur'
        }"
      >
        <el-input v-model="typeDef.displayName"></el-input>
      </el-form-item>
      <el-form-item
        size="mini"
        label="详细说明"
        :label-width="fieldLabelWidth"
        style="margin-top:-10px"
        prop="description"
      >
        <el-input
          type="textarea"
          :rows="3"
          v-model="typeDef.description"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 表布局 -->
    <el-table size="mini" :data="typeDef.fields" style="width: 100%;">
      <el-table-column type="selection" width="25"></el-table-column>
      <el-table-column
        label="序号"
        align="center"
        type="index"
        show-overflow-tooltip
        width="50"
      ></el-table-column>
      <el-table-column width="50"
        ><template slot-scope="scope">
          <i class="el-icon-sort-down" @click="handleDown(scope.$index)"></i>
          <i class="el-icon-sort-up" @click="handleUp(scope.$index)"></i
        ></template>
      </el-table-column>
      <el-table-column
        label="属性名"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column label="必填" align="center" prop="isRequired">
        <template slot-scope="scope">
          {{ scope.row.isRequired }}
        </template>
      </el-table-column>
      <el-table-column label="主键" align="center" prop="isKey">
        <template slot-scope="scope">
          {{ scope.row.isKey }}
        </template>
      </el-table-column>
      <el-table-column
        label="类型"
        align="center"
        prop="type"
      ></el-table-column>
      <el-table-column
        label="显示名"
        align="center"
        prop="displayName"
      ></el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="description"
      ></el-table-column>
      <el-table-column label="操作" width="230px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="handleCopy(scope.$index, scope.row)"
            >复制</el-button
          >
        </template>
      </el-table-column>
      <div slot="append" align="center" style="margin: 5px">
        <el-button @click="handleNewField()" size="mini" type="primary"
          >添加</el-button
        >
      </div>
    </el-table>
    <el-dialog
      title="属性编辑"
      :append-to-body="true"
      :visible.sync="fieldFormVisible"
    >
      <el-form
        :model="fieldOperator"
        align="left"
        ref="fieldForm"
        :rules="fieldFormRules"
      >
        <el-form-item label="属性名" :label-width="fieldLabelWidth" prop="name">
          <el-input v-model="fieldOperator.name"></el-input>
        </el-form-item>
        <el-form-item
          label="显示名"
          :label-width="fieldLabelWidth"
          prop="displayName"
        >
          <el-input v-model="fieldOperator.displayName"></el-input>
        </el-form-item>
        <el-form-item label="类型" :label-width="fieldLabelWidth">
          <el-select v-model="fieldOperator.type" placeholder="请选择属性类型">
            <el-option
              v-for="item in fieldTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="必填" :label-width="fieldLabelWidth">
          <el-select v-model="fieldOperator.isRequired">
            <el-option :key="true" :value="true" label="是"></el-option>
            <el-option :key="false" :value="false" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主键" :label-width="fieldLabelWidth">
          <el-select v-model="fieldOperator.isKey" placeholder="主键">
            <el-option :key="true" :value="true" label="是"></el-option>
            <el-option :key="false" :value="false" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="fieldLabelWidth">
          <el-input type="textarea" v-model="fieldOperator.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleFieldSave()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as schema from '../../api/schema'
import Vue from 'vue'

export default {
  data: function() {
    return {
      fieldFormVisible: false,
      fieldFormRules: {
        name: [{ required: true, message: '请输入属性名', trigger: 'blur' }],
        displayName: [
          { required: true, message: '请输入显示名', trigger: 'blur' }
        ]
      },
      defaultField: {
        name: '',
        type: 'String',
        isRequired: true,
        isKey: false,
        description: ''
      },
      fieldOperator: {},
      fieldLabelWidth: 100 + 'px',
      fieldTypeOptions: [
        {
          label: '文本',
          value: 'String'
        },
        {
          label: 'ID',
          value: 'Id'
        },
        {
          label: '整数',
          value: 'Int'
        },
        {
          label: '数值',
          value: 'Decimal'
        },
        {
          label: '布尔',
          value: 'Boolean'
        },
        {
          label: '密码',
          value: 'Password'
        }
      ],
      openModel: 'new',
      //isEditModel: false, //新建 or 编辑已有对象
      savedTypeDef: {},
      typeDef: {}
    }
  },
  computed: {
    dataChanged: function() {
      if (JSON.stringify(this.savedTypeDef) === JSON.stringify(this.typeDef)) {
        return false
      } else {
        return true
      }
    }
  },
  activated() {
    if (this.$route.query.name) this.openModel = 'update'
    else {
      this.openModel = this.$route.params.openModel
        ? this.$route.params.openModel
        : 'new'
    }
    switch (this.openModel) {
      case 'new':
        if (this.$route.params.typeDef) {
          this.typeDef = this.$route.params.typeDef
          this.typeDef.name = this.typeDef.name + '副本'
          this.savedTypeDef = {}
        } else {
          this.typeDef = {
            group: '',
            name: '',
            fields: []
          }
        }
        break
      case 'update': {
        let schemaName = null
        if (this.$route.params.name) {
          schemaName = this.$route.params.name
        } else if (this.$route.query.name) {
          schemaName = this.$route.query.name
        }
        if (schemaName) {
          let schemaGroup = this.$route.params.group
          this.loadTypeDef(schemaGroup, schemaName)
          this.savedTypeDef = JSON.parse(JSON.stringify(this.typeDef))
        } else {
          this.$message.warning('No schema name provided in $route.params.')
        }
        break
      }
    }
  },
  methods: {
    newField() {
      return JSON.parse(JSON.stringify(this.defaultField))
    },
    handleNewField() {
      // this.typeDef.fields.push();//深度拷贝
      this.fieldOperator = JSON.parse(JSON.stringify(this.newField()))
      this.fieldFormVisible = true
    },
    handleFieldSave() {
      this.$refs['fieldForm'].validate(valid => {
        console.log('检验完成：' + valid)
        if (valid) {
          if (!(this.fieldOperator.index >= 0)) {
            this.typeDef.fields.push(JSON.parse(JSON.stringify(this.fieldOperator))) //深度拷贝，插入数据
          }
          this.fieldFormVisible = false
        } else {
          this.fieldFormVisible = true
        }
      })
    },
    handleDown(index) {
      if (index < this.typeDef.fields.length - 1) {
        let v = this.typeDef.fields[index]
        Vue.set(this.typeDef.fields, index, this.typeDef.fields[index + 1])
        Vue.set(this.typeDef.fields, index + 1, v)
        console.log('array order down: ' + JSON.stringify(this.typeDef.fields))
      } else {
        //do nothing for the last fieldOperator
      }
    },
    handleUp(index) {
      if (index > 0) {
        let v = this.typeDef.fields[index]
        Vue.set(this.typeDef.fields, index, this.typeDef.fields[index - 1])
        Vue.set(this.typeDef.fields, index - 1, v)
        console.log('array order up: ' + JSON.stringify(this.typeDef.fields))
      } else {
        //do nothing for the last fieldOperator
      }
    },
    handleCopy(index, row) {
      this.typeDef.fields.splice(index, 0, JSON.parse(JSON.stringify(row)))
    },
    handleDelete(index) {
      this.typeDef.fields.splice(index, 1)
    },
    handleEdit(index, row) {
      this.fieldOperator = row
      this.fieldOperator.index = index
      this.fieldFormVisible = true
    },
    async loadTypeDef(groupName, typeName) {
      let result = await schema.FINDONE({ group: groupName, name: typeName })
      if (result.code === 0 && result.data) {
        this.typeDef = result.data
        this.openModel = 'update'
        this.savedTypeDef = JSON.parse(JSON.stringify(this.typeDef))
        this.$message.success('模型加载完成！')
      } else {
        this.$message.warning('模型加载失败！')
      }
    },
    async saveTypeDef() {
      let result = await schema.SAVE(this.typeDef)
      if (result.code === 0 && result.data) {
        console.log('Type definition saved:' + JSON.stringify(result.data))
        this.$message.success('模型已保存！')
        await this.loadTypeDef(this.typeDef.group, this.typeDef.name)
      }
    },
    async updateTypeDef() {
      let result = await schema.UPDATE(this.typeDef)
      if (result.code === 0 && result.data) {
        console.log('Type definition saved:' + JSON.stringify(result.data))
        this.$message.success('模型更新已保存！')
        await this.loadTypeDef(this.typeDef.group, this.typeDef.name)
      }
    },
    async handleTypeDelete() {
      let result = await schema.DELETE({
        group: this.typeDef.group,
        type: this.typeDef.name
      })
      if (result.code === 0 && result.data) {
        console.log(
          "Type definition '/" +
            this.typeDef.group +
            '/' +
            this.typeDef.name +
            "' deleted:" +
            JSON.stringify(result.data)
        )
        this.$message.warning('已删除')
        this.$EventBus.$emit('typeDeleted', this.typeDef.name)
        this.$router.go(-1)
      }
    },
    handleTypeUpdate() {
      this.$refs['typeForm'].validate(valid => {
        console.log('typeForm检验完成：' + valid)
        if (valid) {
          this.updateTypeDef()
        }
      })
    },
    handleTypeSave() {
      this.$refs['typeForm'].validate(valid => {
        console.log('typeForm检验完成：' + valid)
        if (valid) {
          this.saveTypeDef()
        }
      })
    },
    back() {
      this.$router.push({
        name: 'DataList',
        params: { group: this.group }
      }) //返回上一层
    }
  }
}
</script>
